package com.vertx.db;

import com.vertx.util.Runner;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.mysqlclient.MySQLConnectOptions;
import io.vertx.mysqlclient.MySQLPool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.SqlConnection;

public class MysqlVerticle extends AbstractVerticle {
	public static void main(String[] args) {

		Runner.runExample(MysqlVerticle.class);

	}

	public void start(Promise<Void> startPromise) throws Exception {

		MySQLConnectOptions connectOptions = new MySQLConnectOptions()
				.setPort(3306)
				.setHost("localhost")
				.setDatabase("testdb")
				.setUser("root")
				.setPassword("water123");

		// Pool options
		PoolOptions poolOptions = new PoolOptions()
				.setMaxSize(5);

		// Create the client pool
		MySQLPool pool = MySQLPool.pool(this.vertx, connectOptions, poolOptions);

		//第一步 获取数据库链接
		pool.getConnection(con -> {
			if(con.succeeded()){
				SqlConnection sqlConnection = con.result();
				//第二步 用获取的数据库链接查询数据库
				sqlConnection.preparedQuery("select * from t_person")
						.execute(rs -> {
							sqlConnection.close();
							//第三步 加工查询出来的数据 并返回给客户端
							if (rs.succeeded()) {
								rs.result().forEach(item -> {
									System.out.println("id : " + item.getInteger(0) + ", first name: " +
											item.getString(1) + ", second name: " + item.getString(2));
								});
							}else {
								System.out.println("fail : " + con.cause().getMessage());
							}
						});
			}else{
				System.out.println("fail : " + con.cause().getMessage());
			}
		});
	}
}
